package com.ys.service.base.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ys.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.AddDto;
import com.ys.entity.base.TbUserMonthPerformance;
import com.ys.entity.base.TbUserMonthPerformanceReport;
import com.ys.entity.base.TbUserMonthPerformanceReportItem;
import com.ys.entity.flow.YspModel;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsCol;
import com.ys.entity.sys.YsMenu;
import com.ys.entity.sys.YsProcInst;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.mapper.base.BaseDiyMapper;
import com.ys.mapper.base.TbUserMonthPerformanceMapper;
import com.ys.mapper.base.TbUserMonthPerformanceReportItemMapper;
import com.ys.mapper.base.TbUserMonthPerformanceReportMapper;
import com.ys.service.base.TbUserMonthPerformanceReportService;
import com.ys.service.flow.YspTaskService;
import com.ys.util.CheckUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;


/**
 * 员工月度绩效申报
 */
@Service("tbUserMonthPerformanceReportService")
public class TbUserMonthPerformanceReportServiceImpl implements TbUserMonthPerformanceReportService {
	private static final Logger logger = LoggerFactory.getLogger(TbUserMonthPerformanceReportServiceImpl.class);

	@Autowired
	private TbUserMonthPerformanceReportMapper tbUserMonthPerformanceReportMapper;

	@Autowired
	private TbUserMonthPerformanceReportItemMapper tbUserMonthPerformanceReportItemMapper;


	@Autowired
	private CheckUtil checkUtil;

	@Autowired
	private YspTaskService yspTaskService;

	@Autowired
	private BaseDiyMapper baseDiyMapper;

	@Autowired
	private TbUserMonthPerformanceMapper tbUserMonthPerformanceMapper;


	/**
	 * 新增
	 */
	@Override
	public R save(Map<String, Object> params, Long menuId) throws Exception{
		logger.info("保存传参:"+params);
		//参数验证
		String errorBack = checkParams(params, menuId);
		if(errorBack!=null && !"".equals(errorBack)){
			return R.error(errorBack);
		}

		TbUserMonthPerformanceReport tbUserMonthPerformanceReport = JSON.parseObject(JSON.toJSONString(params), TbUserMonthPerformanceReport.class);
		tbUserMonthPerformanceReport.setStatus(1);//状态
		tbUserMonthPerformanceReport.setEffectStock(0);//审批状态

		List<Map<String, Object>> paramsNewByItem = new ArrayList<>();
		if(params.get("subData")!=null){
			//验证详情信息
			JSONArray subData = JSON.parseArray(params.get("subData").toString());
			String errorBackByItem = "";//错误信息
			for (int i = 0; i < subData.size(); i++) {
				JSONObject jSONObject = subData.getJSONObject(i);
				Map<String, Object> paramsNewByRecord = new HashMap<>();
				if(jSONObject.get("id")!=null && !"".equals(jSONObject.get("id")))paramsNewByRecord.put("id",jSONObject.get("id"));//id
				if(jSONObject.get("monthPerformanceId")!=null){
					paramsNewByRecord.put("monthPerformanceId",jSONObject.get("monthPerformanceId"));
				}else {
					errorBackByItem += "第"+(i+1)+"行的员工月度绩效信息表Id为空！";
				}
				if(jSONObject.get("hrPerformancePoint")!=null && !"".equals(jSONObject.get("hrPerformancePoint"))){
					//部门绩效评分在0-100
					if(checkUtil.isNotNullByObject(params.get("hrPerformancePoint"))){
						BigDecimal hrPerformancePoint = new BigDecimal(params.get("hrPerformancePoint").toString());
						if(hrPerformancePoint.compareTo(new BigDecimal(100))>0){
							errorBackByItem += "第"+(i+1)+"行的部门绩效评分不能大于100 ";
						}
						if(hrPerformancePoint.compareTo(BigDecimal.ZERO)<0){
							errorBackByItem += "第"+(i+1)+"行的部门绩效评分不能小于0 ";
						}
					}
					paramsNewByRecord.put("hrPerformancePoint",jSONObject.get("hrPerformancePoint"));//人事绩效评分
				}else {
					errorBackByItem += "第"+(i+1)+"行的人事绩效评分为空！";
				}
				if(jSONObject.get("hrPerformanceContent")!=null && !"".equals(jSONObject.get("hrPerformanceContent"))){
					paramsNewByRecord.put("hrPerformanceContent",jSONObject.get("hrPerformanceContent"));//人事绩效内容
				}else {
					errorBackByItem += "第"+(i+1)+"行的人事绩效内容为空！";
				}
				if(jSONObject.get("jobBonus")!=null)paramsNewByRecord.put("jobBonus",jSONObject.get("jobBonus"));//岗位提奖
				if(jSONObject.get("jobBonusExplain")!=null)paramsNewByRecord.put("jobBonusExplain",jSONObject.get("jobBonusExplain"));//岗位提奖说明
				paramsNewByItem.add(paramsNewByRecord);
			}
			if(errorBackByItem!=null && !"".equals(errorBackByItem)){
				return R.error(errorBackByItem);
			}
		}else {
			return R.error("列表信息为空！");
		}

		//获取制单人信息
		TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setOrderby("A.CreateTime DESC").queryFirst();
		if(tsUserChange!=null){
			tbUserMonthPerformanceReport.setCreateChangeId(tsUserChange.getId());//制单人变更信息
		}else {
			R.error("未查询到制单人信息！");
		}
		if(tbUserMonthPerformanceReport.getId()!=null){
			//修改
			tbUserMonthPerformanceReportMapper.update(tbUserMonthPerformanceReport);
		}else {
			//新增
			tbUserMonthPerformanceReportMapper.insert(tbUserMonthPerformanceReport);
		}

		//保存列表信息
		//先删除列表信息
		baseDiyMapper.deleteReportItemByPbid(tbUserMonthPerformanceReport.getBid());
		for (int i = 0; i < paramsNewByItem.size(); i++) {
			Map<String, Object> item = paramsNewByItem.get(i);
			TbUserMonthPerformanceReportItem tbUserMonthPerformanceReportItem = JSON.parseObject(JSON.toJSONString(item), TbUserMonthPerformanceReportItem.class);
			tbUserMonthPerformanceReportItem.setPbid(tbUserMonthPerformanceReport.getBid());
			tbUserMonthPerformanceReportItem.setStatus(1);
			//新增
			tbUserMonthPerformanceReportItemMapper.insert(tbUserMonthPerformanceReportItem);
			/*
			if(tbUserMonthPerformanceReportItem.getId()!=null){
				//修改
				tbUserMonthPerformanceReportItemMapper.update(tbUserMonthPerformanceReportItem);
			}else {
				//新增
				tbUserMonthPerformanceReportItemMapper.insert(tbUserMonthPerformanceReportItem);
			}
			 */
		}

		YsMenu ysMenu = new YsMenu().setId(menuId).queryFirst();
		if (ysMenu.getFlowModelId().longValue() != 0L) {
			YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
			String codeModel = yspModel.getCode();
			String createUserId = ShiroUtils.getUserId();
			yspTaskService.init(codeModel, tbUserMonthPerformanceReport.getBid(), createUserId);
		}
		return R.ok(AddDto.gotoEdit("/web/base/tbUserMonthPerformanceReport/toEdit?bid=" + tbUserMonthPerformanceReport.getBid()));
	}


	/**
	 * 流转通过
	 */
	@Override
	@Transactional
	public R flowPass(Long id, String loginUserId) throws Exception {

		TbUserMonthPerformanceReport entity = new TbUserMonthPerformanceReport().setId(id).queryFirst();
		Flow f = yspTaskService.flowPass(entity.getBid(), loginUserId);
		if (f.getCode() == Flow.Code.FAILED.value) {
			return R.error(f.getMsg());
		} else {
			if (f.getState() == Flow.State.FINISH.value) {
				flowFinish(entity.getBid());
			}
			return R.ok();
		}
	}

	/**
	 * 流转结束
	 */
	@Override
	@Transactional
	public void flowFinish(String bid) throws Exception {

		TbUserMonthPerformanceReport entity = new TbUserMonthPerformanceReport().setBid(bid).queryFirst();
		YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
		if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.FINISH.value) {
			return;
		}
		Date theDate = new Date();
		entity.setEffectStock(FlowEnum.EffectStock.EFFECTED.value);
		entity.setUpdateTime(theDate);

		//修改信息
		tbUserMonthPerformanceReportMapper.update(entity);

		//列表信息
		List<TbUserMonthPerformanceReportItem> itemList = new TbUserMonthPerformanceReportItem().setPbid(entity.getBid()).queryList();
		if(itemList!=null && itemList.size()>0){
			for(TbUserMonthPerformanceReportItem item:itemList){
				TbUserMonthPerformance tbUserMonthPerformance = new TbUserMonthPerformance();
				tbUserMonthPerformance.setId(item.getMonthPerformanceId());
				if(item.getHrPerformancePoint()!=null)tbUserMonthPerformance.setHrPerformancePoint(item.getHrPerformancePoint());
				if(item.getJobBonus()!=null)tbUserMonthPerformance.setJobBonus(item.getJobBonus());
				if(item.getJobBonusExplain()!=null)tbUserMonthPerformance.setJobBonusExplain(item.getJobBonusExplain());
				tbUserMonthPerformanceMapper.update(tbUserMonthPerformance);
			}
		}

	}


	/**
	 * 参数验证
	 */
	public String checkParams(Map<String, Object> params, Long menuId) throws Exception {
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		//验证必填字段的非空；其他字段的长度限制、类型
		String backMsg = checkUtil.checkTableColLengthAndDataType("TB_UserMonthPerformanceReport",listField,params,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);

		return backMsg;
	}



	//删除
	@Override
	@Transactional
	public R del(Long id) throws Exception{
		if (id == null) {
			return R.error("ID不能为空");
		}
		TbUserMonthPerformanceReport entity = new TbUserMonthPerformanceReport().setId(id).queryFirst();
		if (entity.getEffectStock() == FlowEnum.EffectStock.EFFECTED.value) {
			return R.error("已生效数据无法删除");
		}
		// 验证是否制单人
		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setId(entity.getCreateChangeId()).queryFirst();
		if (!tsUserChange.getUserId().equals(loginUserId) && !"admin".equals(loginUserId)) {
			return R.error("非制单人，无法删除");
		}
		//删除列表信息
		baseDiyMapper.deleteReportItemByPbid(entity.getBid());
		//删除
		tbUserMonthPerformanceReportMapper.deleteTrue(id);
		//删除流程
		yspTaskService.flowDelete(entity.getBid(), loginUserId);
		return R.ok();
	}

	//删除列表信息
	@Override
	@Transactional
	public R delByItem(Long id) throws Exception{
		tbUserMonthPerformanceReportItemMapper.deleteTrue(id);
		return R.ok();
	}

	//获取列表数据
	@Override
	@Transactional
	public Map<String,Object> getExtraParam( String bid) throws Exception{
		Map<String, Object> entity = new TbUserMonthPerformanceReport().setBid(bid).queryFirstMap();

		//获取审核时间
		YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
		if(ysProcInst!=null && ysProcInst.getUpdateTime()!=null)entity.put("auditingTime", DateUtil.getYYYY_MM_DD_HH_mm_ss(ysProcInst.getUpdateTime()));

		return entity;
	}
	//获取子列表数据
	@Override
	@Transactional
	public List<Map<String, Object>> getItemList( String bid) throws Exception{
		List<Map<String, Object>> itemList = new TbUserMonthPerformanceReportItem()
				.addLeftJoin("TB_UserMonthPerformance M ON A.MonthPerformanceId = M.Id")//员工月度绩效信息
				.addField("M.Rank AS rank")//岗位职级
				.addField("M.Type AS type")//岗位工种
				.addField("M.PointMonth AS pointMonth")//评定年月

				.addLeftJoin("TS_UserInfo U ON U.UserId = M.UserId")//用户信息表
				.addField("(U.UserId + '/' + U.UserName) AS userName")//工号/姓名

				.addLeftJoin("TS_OrganizationInfo OI ON OI.Orgid = U.DeptId")
				.addField("OI.DeptName AS deptName")//部门

				.addLeftJoin("THR_UserArchives UAS ON UAS.UserId = M.UserId")//用户档案表
				.addField("UAS.UserState AS userState")//员工状态

				.addLeftJoin("TS_OrganizationInfo O ON O.OrgId = M.OrgId")//组织机构表
				.addField("O.OrgName AS orgName")//所属公司
				.setPbid(bid)
				.queryMap();
		return itemList;
	}


}
